/**
 * Created by moyu on 2017/4/7.
 */
const fs = require('fs');
const api = require('express')();
const wrap = require('express-async-wrap');
const moment = require('moment');
const md5 = require('../helpers/md5');
const upload = require('../helpers/upload').upload;
const ObjectId = require('mongodb').ObjectId;
const formidable = require('formidable');
const articleDB = require('../db/article');

// const KEY = ;
const KEYS = ["ee357d9ff3629cc92a86252c757b7ed9", "fd328a414e86c2e691ccf46fd00d68dd"];

api.all('/login', (req, res) => {
    const isRight = KEYS.includes(md5(req.ent.user + '-' + req.ent.pwd));
    if (isRight) {
        req.session.login = true;
    }
    res.normalize(isRight ? 200 : 500, isRight);
});

api.all('/logout', (req, res) => {
    req.session.login = false;
    res.normalize(200);
});


api.all("/emotions", (req, res) => {
    // https://api.weibo.com/2/emotions.json?source=1362404091

    let data = require('../data/weibo.json').reduce((p, a) => {
        p[a.category||"微博"] = p[a.category||"微博"] || [];
        p[a.category||"微博"].push(a);
        return p;
    }, {});
    res.json(data);
//     require('../helpers/forward_request')(
//         req, res, "http://api.weibo.com/2/emotions.json?source=1362404091"
//     );
});

api.use((req, res, next) => {
    if (!req.login) {
        res.normalize(400, "error:" + "please login");
        return;
    }
    next();
});

api.all('/post', (req, res) => {
    req.ent.tags = req.ent.tags.filter(x => !!x);
    if (req.ent.action == 'update') {
        articleDB
            .updateOne({_id: ObjectId(req.ent.id)}, {
                '$set': {
                    title: req.ent.title, tags: req.ent.tags, content: req.ent.content,
                    top: req.ent.top=='true'?1:0
                }
            })
            .then((f) => res.normalize(200, "ok"), (e) => res.normalize(400, "error:" + e))
    } else {
        req.ent.time = new Date();
        articleDB.add(req.ent).then(() => res.normalize(200, "ok"), (e) => res.normalize(400, "error:" + e))
    }
});

api.all('/delete/:id', (req, res) => {
    const id = req.params.id;
    articleDB.delete({_id: ObjectId(id)}).then(() => res.normalize(200, "ok"), (e) => res.normalize(400, "error:" + e))
});

api.all('/upload', (req, res) => {
    const form = new formidable.IncomingForm();

    form.parse(req, (err, fields, files) => {
        if (err) {
            console.error(err);
            return;
        }
        for (let key in files) {
            const file = files[key];
            fs.readFile(file.path, (err, buf) => {
                if (err) {
                    return console.error(err);
                }
                upload(buf).then(data => res.end(data.url), (e) => res.end('上传失败: ' + e))
                    .then(() => {
                        fs.unlink(file.path);
                    });
            })
        }
    })

});

module.exports = api;